package classroom;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.project.institute.DAO.InstituteListFragmentDAO;
import com.project.trac.R;

import core.modules.DatabaseConnector;

public class FileDownload extends InstituteListFragmentDAO {
	
	private TextView tv_downloadedValue;

	private ProgressBar progressBar;
	private AlertDialog.Builder alertDialog_Builder;
	private AlertDialog alertDialog;
	
	private String DOWNLOADPATH = "downloadpath";
	private String HEADER = "header";
	private String FILE = "file";

	private int fileSize;
	private long downloaded;
	
	private int SCHEDULE_UID;
	
	public static ListFragment newInstance(Context context) {
		FileDownload lf = new FileDownload();
		return lf;
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		SCHEDULE_UID = getActivity().getIntent().getExtras().getInt("SCHEDULE_UID");
		
		new AsynchronousTask().execute();	
		
		return (ViewGroup) inflater.inflate(R.layout.generic_list, null);
	}
	
	@Override
	public void onListItemClick(ListView listView, View view, int position, long id) {
		doDownload(DOWNLOADPATH);
		showProgress(FILE);
	}

	// ---------------------------- * Downloader *
	
	private String doDownload(final String downloadPath) {
		
		Thread dx = new Thread() {

			public void run() {
				File root = android.os.Environment.getExternalStorageDirectory();
				File dir = new File(root.getAbsolutePath() + "/TRAC/" + HEADER.replace("%20", " ") + "/" );
				
				if (!dir.exists()) {
					dir.mkdirs();
					Log.w("Directory exists (After creation)", String.valueOf(dir.exists()));
				}
				
				try {
					URL url = new URL(downloadPath);
					URLConnection connection = url.openConnection();
					connection.connect();

					fileSize = connection.getContentLength();
					
					if (fileSize <= 3145728L) {
						
						getActivity().runOnUiThread(new Runnable() {
							public void run() {
								progressBar.setMax(fileSize);
							}
						});

						InputStream input = new BufferedInputStream(url.openStream());
						OutputStream output = new FileOutputStream(dir + "/" + FILE.replace("%20", " "));

						byte bufferLength[] = new byte[1024];
						int received;

						while ((received = input.read(bufferLength)) != -1) {
							downloaded += received;
							output.write(bufferLength, 0, received);
							getActivity().runOnUiThread(new Runnable() {
								public void run() {
									progressBar.setProgress((int) downloaded);
									progressBar.setSecondaryProgress((int) downloaded + 15);
									float per = (downloaded / (float) fileSize) * 100;
									tv_downloadedValue.setText(downloaded + "/" + fileSize + " KB (" +  (double) Math.round(per * 1000) / 1000 + "%)");
									
									Button button = (Button) alertDialog.getButton(AlertDialog.BUTTON_NEUTRAL);
									
									if ((downloaded/fileSize) == 1) {
										button.setText("Done");
									} 
									
									if (downloaded == 0){
										button.setText("Cancel");
									}
								}
							});
							
						}
						
						output.flush();
	    				output.close();
	    				input.close();
	    				
					} else {
						Toast.makeText(getActivity(), "File is larger than 3mb", Toast.LENGTH_SHORT).show();
					}

				} catch (FileNotFoundException e) {
					showError("file not found on server");
				} catch (IOException e) {
					showError("i/o exception");
				}
			}
		};

		dx.start();
		
		return FILE;

	}

	private void showProgress(String fileName) {

		View view = View.inflate(getActivity(), R.layout.generic_progressbar, null);
		TextView text = (TextView) view.findViewById(R.id.tv_fileName);

		alertDialog_Builder = new AlertDialog.Builder(getActivity());
		alertDialog_Builder.setView(view);
		alertDialog_Builder.setIcon(android.R.drawable.ic_dialog_info);

		text.setText("Downloading file : " + fileName.replace("%20", " "));
		tv_downloadedValue = (TextView) view.findViewById(R.id.tv_download_progress);
		tv_downloadedValue.setText("please wait...");
		
		alertDialog_Builder.setNeutralButton("Close", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int id) {
				downloaded = 0;
				fileSize = 0;
				alertDialog.dismiss();
			}
		});
		
		progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
		progressBar.setProgress((int) downloaded);
		progressBar.setSecondaryProgress((int) downloaded + 15);
		progressBar.setProgressDrawable(getResources().getDrawable(R.drawable.progressbar_custom));
		
		alertDialog = alertDialog_Builder.show();
	}
	
	private void showError(final String err) {
		getActivity().runOnUiThread(new Runnable() {
			public void run() {
				Toast.makeText(getActivity(), err, Toast.LENGTH_LONG).show();
			}
		});
	}

	public class AsynchronousTask extends AsyncTask<String, String, String> {

		HashMap<String, String> m;
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();

		ResultSet rs;
		
		String KEY_DOC_NAME = "k1";
		String KEY_HEADER = "k2";


		protected void onPreExecute() {
			super.onPreExecute();
		}

		protected String doInBackground(String... args) {
			
			try {
				rs = DatabaseConnector.getStatement().executeQuery("SELECT name, header FROM documents"
						+ " WHERE cid = " + getSubjectID()
						+ " AND uid = " + SCHEDULE_UID);
				
				while (rs.next()) {

					m = new HashMap<String, String>();
					m.put(KEY_DOC_NAME, rs.getString("name"));
					m.put(KEY_HEADER, rs.getString("header"));
					
					arrayList.add(m);
				
					
					FILE = rs.getString("name").replace(" ", "%20");
					HEADER = rs.getString("header").replace(" ", "%20");
					DOWNLOADPATH = DatabaseConnector.getCatalogDirectory(HEADER.concat("/")).concat(FILE);
				}

			} catch (SQLException e) {
				DatabaseConnector.Logger(getClass(), "doInBackground", e);
			}

			return null;
		}

		protected void onPostExecute(String postExecute) {

			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {

					SimpleAdapter adapter = new SimpleAdapter(getActivity(), arrayList,
							R.layout.student_document_details, 
							new String[] {KEY_DOC_NAME}, 
							new int[] {R.id.header_docName });
					setListAdapter(adapter);

				}

			});
		}
	} 

}